package com.poi.java.util;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class FileUtil {

    public static ResponseEntity downloadFile(File file) throws IOException {

        if (file.exists()) {

            FileSystemResource fileSource = new FileSystemResource(file);

            return downloadFile(fileSource.getInputStream(),fileSource.getFilename());

        }

        return null;

    }

    public static ResponseEntity downloadFile(InputStream in, String fileName) {

        try {

            byte[] testBytes = new byte[in.available()];

            HttpHeaders headers = new HttpHeaders();

            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");

            headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"",fileName));

            headers.add("Pragma", "no-cache");

            headers.add("Expires", "0");

            return ResponseEntity

                    .ok()

                    .headers(headers)

                    .contentLength(testBytes.length)

                    .contentType(MediaType.parseMediaType("application/octet-stream"))

                    .body(new InputStreamResource(in));

        } catch (IOException e) {

            e.printStackTrace();

        }

        return null;

    }


    public static String convertFileName(String fileName) {

//        if(isContainChinese(fileName)) {
//
//            try {
//
//                fileName = URLEncoder.encode(fileName, "UTF-8");
//
//            } catch (UnsupportedEncodingException e) {
//
//                e.printStackTrace();
//
//            }
//
//        }

        return fileName;

    }
}
